﻿using System.Diagnostics;

namespace 取消异步任务;

class Program
{
    static void Main(string[] args)
    {
        Test2();
    }

    public static async void Test1()
    {
        CancellationTokenSource cts = new CancellationTokenSource();
        var toke = cts.Token;

        Stopwatch sw = Stopwatch.StartNew();
        try
        {
            var ca = Task.Run(async () =>
            {
                await Task.Delay(3000);
                cts.Cancel();
            });

            // 一个要等待5秒，一个3秒就结束了
            await Task.WhenAll(Task.Delay(5000, toke), ca);

            Console.WriteLine($"{sw.ElapsedMilliseconds}");
        }
        catch (TaskCanceledException e)
        {
            Console.WriteLine(e);
            Console.WriteLine($"{sw.ElapsedMilliseconds}");
        }
        finally
        {
            cts.Dispose();
        }
    }

    public static async void Test2()
    {
        CancellationTokenSource cts = new CancellationTokenSource(3000);
        var toke = cts.Token;
        
        Stopwatch sw = Stopwatch.StartNew();
        try
        {
            // 一个要等待5秒
            await Task.Delay(5000, toke);
            Console.WriteLine($"{sw.ElapsedMilliseconds}");
        }
        catch (TaskCanceledException e)
        {
            Console.WriteLine(e);
            Console.WriteLine($"{sw.ElapsedMilliseconds}");
        }
        finally
        {
            cts.Dispose();
        }
    }
}